package top.shiyiri.web;

import top.shiyiri.pojo.User;
import top.shiyiri.service.UserService;
import top.shiyiri.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Aunean
 * @date 2022/1/28 20:12
 */
public class RegisterServlet extends HttpServlet {

    private UserService service = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPost");
        //设置字符编码
        req.setCharacterEncoding("utf-8");

        //获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //String repwd = req.getParameter("repwd");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        System.out.println("username = " + username + ", password = " + password);
        System.out.println("email = " + email + ", code = " + code);
        //检查验证码是否正确
        if ("6n6np".equalsIgnoreCase(code)) {
            //检查用户名是否可用
            if (service.existsUsername(username)) {
                //不可用
                System.out.println("用户名已存在");
                req.setAttribute("msg", "用户名已存在！");
                req.setAttribute("username", username);
                req.setAttribute("email", email);
                req.setAttribute("password", password);
                req.setAttribute("code", code);
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
            } else {
                //可用
                //调用service层保存到数据库
                service.register(new User(null, username, password, email));
                resp.sendRedirect("http://localhost:8080/book/pages/user/regist_success.jsp");
            }
        } else {
            //跳回注册页面
            req.setAttribute("msg", "验证码错误！");
            req.setAttribute("username", username);
            req.setAttribute("email", email);
            req.setAttribute("password", password);
            req.setAttribute("code", code);

            System.out.println("验证码["+code+"]错误");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
